<?php

namespace app\common\model\Post;

use think\Model;
use traits\model\SoftDelete;

class Post extends Model
{
    use SoftDelete;

    //标志当前模型操作的是哪张表
    protected $name = "post";

    //开启自动写入
    protected $autoWriteTimestamp = true;

    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'status_text',
        'createtime_text',     // 课程创建时间（时间戳转换成年月日）
        'comment_text',
        'collect_text'
    ];

    // --------------------------------- 获取器 ---------------------------------

    // 帖子解决未解决状态
    public function statuslist()
    {
        return [
            '0' => __('未解决'),
            '1' => __('已解决'),
        ];
    }
    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->statuslist();
        return isset($list[$value]) ? $list[$value] : '';
    }

    // 帖子创建时间戳转换
    public function getCreateTimeTextAttr($value, $data)
    {
        $createtime = isset($data['createtime']) ? trim($data['createtime']) : '';

        if (empty($createtime)) {
            return '';
        }
        return date("Y-m-d H:i", $createtime);
    }

    // 统计帖子评论人数
    public function getCommentTextAttr($value, $data)
    {
        $postid = $data['id'];

        $count = model('Post.Comment')->where(['postid' => $postid])->group('busid')->count();

        return $count ? $count : 0;
    }

    // 统计帖子收藏人数
    public function getCollectTextAttr($value, $data)
    {
        $postid = $data['id'];

        $count = model('Post.Collect')->where(['postid' => $postid])->count();

        return $count ? $count : 0;
    }

    // --------------------------------- 连表查询 ---------------------------------
    public function business()
    {
        return $this->belongsTo('app\common\model\Business\Business', 'busid', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function cate()
    {
        return $this->belongsTo('app\common\model\Post\Cate', 'cateid', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function comment()
    {
        return $this->belongsTo('app\common\model\Post\Comment', 'id', 'postid', [], 'LEFT')->setEagerlyType(0);
    }
    public function collect()
    {
        return $this->belongsTo('app\common\model\Post\collect', 'id', 'postid', [], 'LEFT')->setEagerlyType(0);
    }
}
